<script setup>
import { ref } from 'vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { Api } from '@/api'
import {baseURL} from '@/utils/request.js'
import base from '@/api/base.js'
import {useUserStore}from '@/stores/user.js'

const uploadFileUrl = base.baseUrl + base.uploadFiles
const visibleDrawer = ref(false)
// 控制抽屉的显示和隐藏
const articleEditRef = ref()
const userStore = useUserStore()
const token = ref(userStore.token)
//默认数据
const defaultForm={
  title: '',
  picture: '',//封面
  content: '',
  state: ''//状态
}
//准备数据
const formModel = ref({
  ...defaultForm,
})


const fileUrl = ref('')
/*
// 上传图片
const imgUrl = ref('')
const onUploadFile = (uploadFile) => {
  imgUrl.value = URL.createObjectURL(uploadFile.raw)
  formModel.value.picture = uploadFile.raw
}
*/
// 上传图片
const handleSuccess = (res, file, fileList) => {
  if (res.status === 200) {
    const uploadedUrl = res.data.filePath // 修改为正确的返回字段
    fileList.forEach((item) => {
      if (item.uid === file.uid) {
        item.url = uploadedUrl // 更新文件列表中的 URL
      }
    })
    if (!Array.isArray(formModel.value.picture)) {
      formModel.value.picture = [] // 确保 picture 字段为数组
    }
    formModel.value.picture.push(uploadedUrl) // 将图片 URL 添加到数组中
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error('图片上传失败')
  }
}

//检查图片形式
const beforeAvatarUpload = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('必须是jpg或者png图片');
        return false;
    } else if (rawFile.size / 99999 / 9999 > 2) {
        return false;
    }
    return true;
};
//图片预览
const handlePictureCardPreview = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url;
    dialogVisible.value = true;
};

// 图片移除逻辑
const handleRemove = (file, fileList) => {
  console.log('移除的文件:', file)
  console.log('当前文件列表:', fileList)
  formModel.value.picture = formModel.value.picture.filter((url) => url !== file.url) // 从数组中移除对应的 URL
  ElMessage.info('图片已移除')
}

// 发布文章
const emit = defineEmits(['success'])
const onPublish = async (state) => {
  try {
    // 校验必填字段
    if (!formModel.value.title.trim()) {
      ElMessage.error('文章标题不能为空');
      return;
    }
    if (!formModel.value.content.trim()) {
      ElMessage.error('文章内容不能为空');
      return;
    }

    // 将已发布还是草稿状态，存入 state
    formModel.value.state = state;

    const payload = {
      //id: formModel.value.id || undefined, // 如果是新增文章，省略 id
      title: formModel.value.title,
      content: formModel.value.content,
      picture: JSON.stringify(formModel.value.picture || []), // 确保 picture 字段为 JSON 字符串
    };

    console.log('发送到后端的 JSON 对象:', payload); // 调试输出

    if (formModel.value.id) {
      // 编辑文章
      await Api.updatePsychologyKnowledge(formModel.value.id, payload) // 发送 JSON 数据

      ElMessage.success('编辑成功');
      emit('success', 'edit');
    } else {
      // 添加文章
      await Api.addPsychologyKnowledge(payload) // 发送 JSON 数据

      ElMessage.success('添加成功');
      emit('success', 'add');
    }

    visibleDrawer.value = false; // 关闭抽屉
  } catch (error) {
    console.error('发布文章失败:', error);
    ElMessage.error('发布文章失败，请稍后再试');
  }
}
//重置
const formRef = ref()
const editorRef = ref()
const fileList = ref([]) 
const open = async (id) => {
  try {
    visibleDrawer.value = true
     console.log('open() called with id:', id) // 调试
    if (id) {
      console.log('编辑回显，文章 ID:', id)
      const res = await Api.getPsychologyKnowledgeById({ id })
      const targetArticle = res.data.data
      if (targetArticle) {
        formModel.value = { ...targetArticle }
        // 解析 picture 字段为数组
        const pictures = JSON.parse(targetArticle.picture || '[]')
        fileList.value = pictures.map((url) => ({
          name: '图片',
          url: baseURL + url, // 拼接完整图片 URL
        }))
      } else {
        throw new Error('未找到对应的文章数据')
      }
    } else {
      formModel.value = { ...defaultForm }
      fileList.value = []
    }
  } catch (error) {
    console.error('加载文章数据失败:', error)
    ElMessage.error('加载文章数据失败，请稍后再试')
    visibleDrawer.value = false
  }
}

// 编辑新增逻辑
const onAddArticle = () => {
  articleEditRef.value.open({})
}
const onEditArticle = (row) => {
  articleEditRef.value.open(row)
}
//向外暴露
defineExpose({
  open
})
</script>

<template>
  <el-drawer
    v-model="visibleDrawer"
    :title="formModel.id ? '编辑文章' : '添加文章'"
    direction="rtl"
    size="50%"
  >
    <!-- 发表文章表单 -->
    <el-form :model="formModel" ref="formRef" label-width="100px">
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="formModel.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="文章封面" prop="picture">
        <el-upload
          class="avatar-uploader"
          :action="uploadFileUrl"
          list-type="picture-card"
          :file-list="fileList"
          :on-success="handleSuccess"
          :before-upload="beforeAvatarUpload"
          :on-remove="handleRemove"
          :headers="{ Authorization: 'Bearer ' + token }"
        >
          <Plus /> <!-- 使用默认插槽内容 -->
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容" prop="content">
        <div class="editor">
          <quill-editor
            theme="snow"
            v-model:content="formModel.content"
            contentType="html"
          ></quill-editor>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button @click="onPublish('已发布')" type="primary">发布</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
//fuwenben
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
